#pragma once

#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <unordered_map>

const std::string blankSym = "\r\n";
const std::string webRoot = "./wwwroot";
const std::string homePage = "/index.html";
const std::string errPage = "/err.html";

class httpRequest
{
public:
    // 学习需要，忽略异常处理
    void deserializa(const std::string &mesg)
    {
        size_t head = 0;
        while (true)
        {
            size_t pos = mesg.find(blankSym, head);
            std::string mesgHead = mesg.substr(head, pos - head);
            head = pos + 2;
            // 如果读到了空行，说明报头部分已经结束了
            if (mesgHead.empty())
                break;
            _header.push_back(std::move(mesgHead));
        }
        // 处理文本部分
        _content = mesg.substr(head);
    }

    void parse()
    {
        // 从第一行中解析出状态行表示的内容
        std::stringstream sstrem(_header[0]);
        sstrem >> _mode >> _url >> _httpVersion;

        // 处理索要访问的文件路径
        _filePath = webRoot;
        if (_url == "/")
            _filePath += homePage;
        else
            _filePath += _url;
        size_t rpos = _filePath.rfind('.');
        if (rpos != std::string::npos)
            _type = _filePath.substr(rpos);
        // 在分析的时候顺便拿到请求的资源的类型
    }

    void debugPrint()
    {
        for (const auto &e : _header)
        {
            std::cout << "=========================\n";
            std::cout << e << std::endl;
        }
        std::cout << std::endl;
        std::cout << "mode: " << _mode << std::endl;
        std::cout << "_url: " << _url << std::endl;
        std::cout << "_httpVersion: " << _httpVersion << std::endl
                  << std::endl;
    }

public:
    // 报头
    std::vector<std::string> _header;
    std::string _content;

    // 解析后的内容
    std::string _httpVersion;
    std::string _mode;
    std::string _url;
    // filePath通过url获得请求索要访问的web数据
    std::string _filePath;
    std::string _type;
};